package com.yupi.mybi.controller;


import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.hutool.http.ContentType.JSON;

/**
 * 帖子接口
 */
@RestController
@RequestMapping("/queue")
@Profile({"dev","local"})
@Slf4j
public class ThreadPoolController {
    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/add")
    public void add(String name){
        CompletableFuture.runAsync(() -> {
            System.out.println("线程" + Thread.currentThread() + "正在执行任务:" + name);
            System.out.println(Thread.currentThread());
            try {
                Thread.sleep(6000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },threadPoolExecutor);
    }

    @GetMapping("/get")
    public String get(){
        Map<String,Object> map = new HashMap<>();
        int size = threadPoolExecutor.getQueue().size();
        map.put("队列长度:",size);
        long taskCount = threadPoolExecutor.getTaskCount();
        map.put("任务总数:",taskCount);
        long completedTaskCount = threadPoolExecutor.getCompletedTaskCount();
        map.put("执行完的任务数:",completedTaskCount);
        int activeCount = threadPoolExecutor.getActiveCount();
        map.put("正在工作的线程数:",activeCount);

        return JSONUtil.toJsonStr(map);
    }

}
